package cn.offcn.service.Impl;

import cn.offcn.entity.*;
import cn.offcn.mapper.DeptMapper;
import cn.offcn.mapper.EmpRoleMapper;
import cn.offcn.mapper.EmployeeMapper;
import cn.offcn.mapper.RoleMapper;
import cn.offcn.service.EmployeeService;
import cn.offcn.utils.OAResult;
import cn.offcn.utils.TableVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author yuliantao
 * @create 2020 -09 -2020-09-21 21:52
 * @description 功能描述
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Value("${uploadDir}")
    private  String uploadDir;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private EmpRoleMapper empRoleMapper;
    @Override
    public Map<String, Object> getAllDeptAndRole() {
        List<Dept> deptList = deptMapper.selectByExample(new DeptExample());

        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andStatusEqualTo(1);
        List<Role> roleList = roleMapper.selectByExample(new RoleExample());
          Map<String ,Object> map =new HashMap<>();
          map.put("depts",deptList);
          map.put("roles",roleList);
        return map  ;
    }

    @Override
    public OAResult addEmployee(Employee employee, int roleid, MultipartFile uploadPic) {
        if (uploadPic!=null && uploadPic.getSize()>0){
            try {
                String fileName = uploadPic.getOriginalFilename();
                int d1=fileName.hashCode()&0xf;
                int d2=(d1>>2)&0xf;
                File saveDir = new File(uploadDir + "\\images" + "\\" + d1 + "\\" + d2);
                if (!saveDir.exists()) {saveDir.mkdirs();}
                String extName=fileName.substring(fileName.lastIndexOf("."));
                String newFileName = UUID.randomUUID().toString() + extName;
                File file = new File(saveDir, newFileName);
                uploadPic.transferTo(file);
                employee.setPic("/pic/images/"+d1+"/"+d2+"/"+newFileName);
            } catch (IOException e) {
                e.printStackTrace();
                return OAResult.ok(400,"头像上传失败");
            }

        }
        employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));
        int insert = employeeMapper.insert(employee);

        EmpRole empRole = new EmpRole();
        empRole.setEmpFk(employee.getEid());
        empRole.setRoleFk(roleid);

        int insert1 = empRoleMapper.insert(empRole);
        if (insert==1&&insert1==1){
            return OAResult.ok(200,"操作成功");
        }

        return OAResult.ok(400,"操作失败");
    }

    @Override
    public TableVo<EmployeeVo> getEmployeesInfo(int page, int limit) {

        PageHelper.startPage(page,limit);

        List<Employee> employeeList = employeeMapper.selectByExample(new EmployeeExample());

        PageInfo <Employee> pageInfo =new PageInfo<>(employeeList);
        TableVo<EmployeeVo> tableVo = new TableVo<>();

        tableVo.setCount(pageInfo.getTotal());

        List<Employee> currentEmpList = pageInfo.getList();

        List<EmployeeVo> employeeVoList=new ArrayList<>();

        for (Employee employee : currentEmpList) {
            EmployeeVo employeeVo = new EmployeeVo(employee);

            employeeVo.setDeptName(deptMapper.selectByPrimaryKey(employee.getDfk()).getDname());

            EmpRoleExample empRoleExample = new EmpRoleExample();

            EmpRoleExample.Criteria criteria = empRoleExample.createCriteria();
            criteria.andEmpFkEqualTo(employee.getEid());

            List<EmpRole> empRoles = empRoleMapper.selectByExample(empRoleExample);

            if (empRoles!=null&&empRoles.size()>0){
                String roleName= roleMapper.selectByPrimaryKey(empRoles.get(0).getRoleFk()).getRolename();

                employeeVo.setRoleName(roleName);
            }

        employeeVoList.add(employeeVo);
        }
        tableVo.setData(employeeVoList);

        return  tableVo;
    }

    @Override
    public Map<String,Object> getEmployeeByEid(int eid) {
        Map<String,Object> map = new HashMap<>();

        Employee employee = employeeMapper.selectByPrimaryKey(eid);

        EmpRoleExample empRoleExample = new EmpRoleExample();
        EmpRoleExample.Criteria criteria = empRoleExample.createCriteria();
        criteria.andEmpFkEqualTo(eid);

        List<EmpRole> empRoleList = empRoleMapper.selectByExample(empRoleExample);
        Integer roleid = empRoleList.get(0).getRoleFk();

        map.put("employee",employee);
        map.put("roleid",roleid);

        return map;
    }

    @Override
    public OAResult updateEmployeeByEid(Employee employee, int roleid, MultipartFile uploadPic) {
        if (uploadPic != null && uploadPic.getSize() > 0) {
            try {
                String fileName = uploadPic.getOriginalFilename();
                int d1 = fileName.hashCode() & 0xf;
                int d2 = (d1 >> 2) & 0xf;
                File saveDir = new File(uploadDir + "\\images" + "\\" + d1 + "\\" + d2);
                if (!saveDir.exists()) {
                    saveDir.mkdirs();
                }
                ;
                String extName = fileName.substring(fileName.lastIndexOf("."));
                String newFileName = UUID.randomUUID().toString() + extName;
                File saveFile = new File(saveDir, newFileName);
                uploadPic.transferTo(saveFile);
                //设置头像的路径
                employee.setPic("/pic/images/" + d1 + "/" + d2 + "/" + newFileName);
            } catch (IOException e) {
                e.printStackTrace();
                return OAResult.ok(400, "上传头像失败");
            }
        }

        Employee oldEmployee = employeeMapper.selectByPrimaryKey(employee.getEid());

            if (StringUtils.isNotBlank(employee.getPassword())){
                employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));
            }else{
                employee.setPassword(oldEmployee.getPassword());
            }
        if(!StringUtils.isNotBlank(employee.getPic())){
            employee.setPic(oldEmployee.getPic());
        }
        int rows1 = employeeMapper.updateByPrimaryKey(employee);

        EmpRoleExample empRoleExample = new EmpRoleExample();
        EmpRoleExample.Criteria criteria = empRoleExample.createCriteria();
        criteria.andEmpFkEqualTo(employee.getEid());
        int rows2 = empRoleMapper.deleteByExample(empRoleExample);

        if(rows1==1 && rows2==1){
            return OAResult.ok(200,"操作成功");
        }
        return OAResult.ok(400,"操作失败");
    }

    @Override
    public OAResult deleteEmployeeByEids(int[] eids) {
        if (eids!=null&&eids.length>0){

            for (int eid : eids) {
                EmpRoleExample empRoleExample = new EmpRoleExample();
                EmpRoleExample.Criteria criteria = empRoleExample.createCriteria();
                criteria.andEmpFkEqualTo(eid);

                empRoleMapper.deleteByExample(empRoleExample);

                employeeMapper.deleteByPrimaryKey(eid);

            }
            return OAResult.ok(200,"删除成功");
        }
        return OAResult.ok(400,"删除失败");
    }

    @Override
    public OAResult checkLogin(String username, String password) {
        EmployeeExample employeeExample = new EmployeeExample();
        EmployeeExample.Criteria criteria = employeeExample.createCriteria();
        criteria.andPasswordEqualTo(DigestUtils.md5DigestAsHex(password.getBytes()));
        criteria.andUsernameEqualTo(username);
        List<Employee> employeeList = employeeMapper.selectByExample(employeeExample);

        if (employeeList!=null&&employeeList.size()>0){
            Employee employee = employeeList.get(0);
            String roleName = getEmployeeRoleName(employee.getEid());

                employee.setRoleName(roleName);

            return OAResult.build(200,"登陆成功！·",employee);
        }

        return OAResult.ok(400,"登陆失败！·");
    }


    public  String  getEmployeeRoleName(int eid){
        EmpRoleExample empRoleExample = new EmpRoleExample();
        EmpRoleExample.Criteria criteria = empRoleExample.createCriteria();
        criteria.andEmpFkEqualTo(eid);

        List<EmpRole> empRoleList = empRoleMapper.selectByExample(empRoleExample);

        if (empRoleList!=null && empRoleList.size()>0){

            return roleMapper.selectByPrimaryKey(empRoleList.get(0).getRoleFk()).getRolename();

        }

        return null;
    }
}
